<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天窗口</title>
</head>
<body>
<input id="myname"><button onclick="conn()">连接</button>
<br><br>
<textarea cols="30" id="msgs"></textarea><br>
<input id="mymsg" size="20"><button onclick="send(mymsg.value)">发送</button>

<script>
    var websocket;
    function conn(){
        // 创建websocket对象
        websocket = new WebSocket("ws://localhost/ws/" + myname.value);
        //连接发生错误的回调方法
        websocket.onerror = function(event){
            console.info(event);
            alert("连接出错");
        };
        //连接成功建立的回调方法
        websocket.onopen = function(event){
            console.info(event);
            alert("连接成功!");
        }
        //接收到消息的回调方法
        websocket.onmessage = function(event){
            console.info(msgs.innerText);
            msgs.innerHTML = msgs.innerHTML + event.data + "\r\n";
        }
        //连接关闭的回调方法
        websocket.onclose = function(){
            console.info(event);
            alert("连接关闭");
        }
    }
    //关闭连接
    function closeWebSocket(){ websocket.close(); }
    //发送消息
    function send(msg){
        websocket.send(myname.value + "说: " + msg);
        mymsg.value = "";
        msgs.innerHTML = msgs.innerHTML + myname.value + "说: " + msg + "\r\n";
    }




</script>
</body>
</html>